#include "board.h"
#include <k_api.h>
#include <log.h>

static ktask_t *g_main_task;
#define OS_MAIN_TASK_STACK (128)
#define OS_MAIN_TASK_PRI 50
extern int application_start(void);

void SysTick_Handler(void) {
    krhino_intrpt_enter();
    krhino_tick_proc();
    krhino_intrpt_exit();
}

static void clk_event_handler(nrfx_clock_evt_type_t event) {}

void SysTick_Configuration(void) {
    nrfx_clock_init(clk_event_handler);
    nrfx_clock_enable();
    nrfx_clock_lfclk_start();
    nrfx_clock_hfclk_start();
    /* Set interrupt priority */
    NVIC_SetPriority(SysTick_IRQn, 0xf);

    /* Configure SysTick to interrupt at the requested rate. */
    nrf_systick_load_set(SystemCoreClock / RHINO_CONFIG_TICKS_PER_SECOND);
    nrf_systick_val_clear();
    nrf_systick_csr_set(NRF_SYSTICK_CSR_CLKSOURCE_CPU |
                        NRF_SYSTICK_CSR_TICKINT_ENABLE |
                        NRF_SYSTICK_CSR_ENABLE);
}

void soc_init(void) {
    nrf_gpio_cfg_output(6);
    nrf_gpio_pin_set(6);
    nrf_gpio_cfg_output(8);
    nrf_gpio_pin_set(8);
    nrf_gpio_cfg_output(41);
    nrf_gpio_pin_set(41);
    nrf_gpio_cfg_output(12);
    nrf_gpio_pin_set(12);

    SysTick_Configuration();

#ifdef AOS_COMP_TRACE
    extern void trace_init(void);
    trace_init();
#endif
}

int main(void) {

    soc_init();
    LOG_DEBUG(LOG_MODULE, "soc init");
    krhino_init();

    /*main task to run */
    krhino_task_dyn_create(&g_main_task, "main_task", 0, OS_MAIN_TASK_PRI, 0,
                           OS_MAIN_TASK_STACK, (task_entry_t)application_start,
                           1);
    /*kernel start schedule!*/
    krhino_start();

    /*never run here*/
    while (1) {
        krhino_task_sleep(100);
    }

    return 0;
}
